package com.sfac.springboot.modules.common.service.impl;

import com.sfac.springboot.config.ResourceConfigBean;
import com.sfac.springboot.modules.common.service.ImageService;
import com.sfac.springboot.modules.common.vo.Result;
import com.sfac.springboot.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author jzq
 * @date 2022/8/23 10:25
 */
@SuppressWarnings({"all"})
@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ResourceConfigBean resourceConfigBean;

    public static final Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);

    @Value("${project.artifactId}")
    private String artifactId;

    @Override
    public Result<String> uploadImage(MultipartFile file, String imageTypeName) {
        //判断图片是否为空
        if (file.isEmpty()) {
            return new Result<>(Result.ResultStatus.FAILED.code, "file is empty!");
        }
        //对图片进行校验
        if (FileUtil.isImage(file)) {
            return new Result<>(Result.ResultStatus.FAILED.code, "please select a image!");
        }
        //图片重命名
        String imageName = String.format("%s.%s",
                System.currentTimeMillis(),
                FileUtil.getFileType(file.getOriginalFilename()));

        //构建目标文件夹，不存在则创建
        String destFolder = String.format("%s/%s",
                System.getProperty("os.name").toLowerCase().startsWith("win") ?
                        resourceConfigBean.getLocalPathForWindows() :
                        resourceConfigBean.getLocalPathForLinux(),
                artifactId, imageTypeName
        );
        File destFolderFile = new File(destFolder);
        if (!destFolderFile.exists()) {
            destFolderFile.mkdirs();
        }

        //构造图片存放的绝对路径
        String destPath = String.format("%s/%s",
                destFolder, imageName
        );
        //构造图片的相对路径
        String relativePath = String.format("%s%s/%s/%s",
                resourceConfigBean.getResourcePath(),
                artifactId, imageTypeName, imageName
        );
        //保存图片
        try {
            file.transferTo(new File(destPath));
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.info(e.getMessage());
            return new Result<>(Result.ResultStatus.FAILED.code, "upload image failed!");
        }
        //返回结果集
        return new Result<>(Result.ResultStatus.FAILED.code, "upload image success!");
    }

}
